from typing import List
import math
import csv
import sys


def get_autocorrelation(seqpair):
    n = len(seqpair[0])
    autocorrelation = []
    for shift in range(n):
        sum = 0
        for i in range(n - shift):
            sum += seqpair[0][i] * seqpair[1][i + shift]
        autocorrelation.append(sum)
    return autocorrelation


def is_barker_pair(autocorrelation):
    if autocorrelation[0] <= 1 and autocorrelation[0] >= -1:  # 主峰要大
        return False
    if max(autocorrelation[1:]) <= 1 and min(autocorrelation[1:]) >= -1:  # 副峰要小
        return True
    else:
        return False


def get_mth_sequence(n: int, m: int) -> List[int]:
    sequence = [0] * n
    for i in range(n):
        if m <= 2**(n-i-1):
            sequence[i] = 1
        else:
            sequence[i] = -1
            m -= 2**(n-i-1)

    return sequence


if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("Please provide an integer argument.")
        sys.exit(1)
    length = int(sys.argv[1])
    print("The provided integer is:", length)
    filename = f'{length}.csv'
    with open(filename, 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(["length", "main peak", "main peak/length", "seqpair", "autocorrelation"])
        for i in range(1, 2**length+1):
            x = get_mth_sequence(length, i)
            for j in range(i+1, 2**length+1):
                y = get_mth_sequence(length, j)
                seqpair = [x, y]
                autocorrelation = get_autocorrelation(seqpair)
                b = is_barker_pair(autocorrelation)
                if (b):
                    writer.writerow([length, autocorrelation[0], autocorrelation[0]/length, seqpair, autocorrelation])
